<?php
namespace app\admin\controller;
use app\service\apiService;
use app\service\communityService;
use app\service\propertyService;
use think\facade\Db;
use think\facade\View;

class Community extends Common{
    //查询小区信息
    public function communityList(){
        $com = $this->pidTokenId();

        $where[] =['community_id','in',$com['community_id']];
        $data = request()->get();
        if (!empty($data)){
            if(!empty($data['community_name'])){
                //$where['community_name'] = array("like","%".$data['community_name']."%");//账单编号
                $where[] =['community_name',"like","%".$data['community_name']."%"];
            }
        }
        $where = array_filter($where);
        //查询小区信息
        $number = count((new communityService())->communityNumber($where));
        View::assign('number', $number);
        $communitylist = (new communityService())->communityList($where);

        if(!empty($number)){
            foreach($communitylist as $lis){
                $propertyzftInfo= (new propertyService())->getZftInfo($lis["property_id"]);
                //
                $lis["binding_alipay_logon_id"]=$propertyzftInfo["binding_alipay_logon_id"];
                $lis['property_id'] = (new communityService())->propertyIdName($lis['property_id']);
                $list[] = $lis;
            }
            View::assign('list', $list);
        }else{
            View::assign('list', $communitylist);
        }
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }
        return View::fetch('community_list');
    }
    //查询小区信息
    public function communityset(){
        $com = $this->pidTokenId();
        $where[] =['community_id','in',$com['community_id']];
        $data = request()->get();
        if (!empty($data)){
            if(!empty($data['community_name'])){
                //$where['community_name'] = array("like","%".$data['community_name']."%");//账单编号
                $where[] =['community_name',"like","%".$data['community_name']."%"];
            }
        }
        $where = array_filter($where);
        //查询小区信息
        $number = count((new communityService())->communityNumber($where));
        View::assign('number', $number);
        $communitylist = (new communityService())->communityList($where);

        if(!empty($number)){
            foreach($communitylist as $lis){
                $lis['property_id'] = (new communityService())->propertyIdName($lis['property_id']);
                $list[] = $lis;
            }
            View::assign('list', $list);
        }else{
            View::assign('list', $communitylist);
        }
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }
        return View::fetch('community_set');
    }
    //添加小区信息
    public function communityAdd(){
        //根据当前账号查询物业信息
        $com = $this->pidTokenId();
        //$where['id'] = array('in',$com['property_id']);
        //$where[]=[]
        $where[] = ['id','in',$com["property_id"]];
        $propertylist =(new communityService())->propertyList($where);
        View::assign('propertylist',$propertylist);
        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();
            //判断小区是否重复
            $info = (new communityService())->communityName($data['community_name']);
            if($info){
                $this->error('小区已存在');
            }
            
            $data["community_id"]=$this->getCommunityId($data["city_code"]);
            
            $data['time'] = date('Y-m-d H:i:s',time());
            $data['status'] = communityService::STATUS_SYNC;
            //将数据插入数据库
            $result = (new communityService())->communityAdd($data);
            //判断数据是否插入成功
            if($result){
                $this->success('添加小区成功',url('communitylist'));
            }else{
                $this->error('添加小区失败',url('communityAdd'));
            }
        }else{
            return View::fetch('community_add');
        }
    }
    public function test(){
        $city_code="330100";  
        var_dump($this->getCommunityId($city_code));  
    }
    public function getCommunityId($city_code){
        $arr=['A','B','C','D','E','F','G','H','I','G','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'];
        $str=$arr[mt_rand(0, count($arr) - 1)].$arr[mt_rand(0, count($arr) - 1)].$arr[mt_rand(0, count($arr) - 1)].$arr[mt_rand(0, count($arr) - 1)].$arr[mt_rand(0, count($arr) - 1)].$arr[mt_rand(0, count($arr) - 1)].$arr[mt_rand(0, count($arr) - 1)].$arr[mt_rand(0, count($arr) - 1)];
        $community_id="A".$str.substr($city_code,0,4);
        $communityinfo=Db::table("community")->where("community_id",$community_id)->find();
        if(empty($communityinfo)){
            return $community_id;
        }else{
            return $this->getCommunityId($city_code);
        }
    }
    //同步小区到支付宝
    public function synchronization(){
        if (!request()->has('id') && empty(request()->param('id'))) {
            return json(['error' => '错误']);
        }
        //根据ID查询小区数据
        $id = request()->param('id');
        $data = (new communityService())->communityIdInfo($id);
        //根据小区ID查询物业信息
        $property = (new communityService())->propertyToken($data['property_id']);
        $api = new apiService(config('app')['create'], 'https://openapi.alipay.com/gateway.do');
        $res = $api->create(json_encode(['community_name' => $data['community_name'], 'community_address' =>  $data['community_address'], 'district_code' => $data['district_code'],'city_code' => $data['city_code'], 'province_code' => $data['province_code'], 'community_locations' => $data['community_locations'], 'hotline' => $data['hotline'], 'token' => $property['accredit']]));

        if (!isset($res['error'])) {
            $info['community_id'] = $res;
            $info['id'] = $data['id'];
            $info['state']  = 2;
            $result = (new communityService())->communityIdEdit($info);
            //判断数据是否插入成功
            if($result){
                return json(['info' => '小区同步支付宝成功']);
            }else{
                return json(['error' => $res['error']]);
            }
        }else{
            return json(['error' => $res['error']]);
        }
    }

    //初始化小区信息
    public function initialize(){
        if (!request()->has('id') && empty(request()->param('id'))) {
            return json(['error' => '错误']);
        }

        //根据ID查询小区数据
        $id = request()->param('id');
        $data = (new communityService())->communityIdInfo($id);
        //根据物业ID查询token
        $property = (new communityService())->propertyToken($data['property_id']);

        $api = new apiService(config('app')['initialize'], 'https://openapi.alipay.com/gateway.do');
        $res = $api->initialize(json_encode(['community_id' => $data['community_id'], 'external_invoke_address' => config('app')['notify'], 'account' => $property['merchantpid'], 'token' => $property['accredit']]));

        //同步支付宝状态
        if (isset($res['success'])) {
            $api = new apiService(config('app')['find'], 'https://openapi.alipay.com/gateway.do');
            $resy = $api->fecthCommunityByCommunityId($data['community_id'],$property['accredit']);

            if (isset($resy['success'])) {
                $data['twocode'] = $resy['success']->community_services[0]->qr_code_image;
                $data['status'] = $resy['success']->community_status;
                $data['state']  = 3;
                $res = (new communityService())->communityEdit($data['community_id'], $data);
                return json(['info' => '初始化成功']);
            }else{
                return json(['error' => $res['error']]);
            }
        }else{
            return json(['error' => $res['error']]);
        }
    }

    //改变小区状态
    public function basicservice(){
        if (!request()->has('id') && empty(request()->param('id'))) {
            return json(['error' => '错误']);
        }
        
        //根据ID查询小区数据
        $id = request()->param('id');
        $data = (new communityService())->communityIdInfo($id);
        //根据物业ID查询token
        $property = (new communityService())->propertyToken($data['property_id']);

        $api = new apiService(config('app')['basicservice'], 'https://openapi.alipay.com/gateway.do');
        $res = $api->basicservice(json_encode(['community_id' => $data['community_id'], 'external_invoke_address' => config('app')['notify'], 'account' => $property['merchantpid'], 'token' => $property['accredit']]));
        //同步支付宝状态
        if (isset($res['success'])) {
            $api = new apiService(config('app')['find'], 'https://openapi.alipay.com/gateway.do');
            $resy = $api->fecthCommunityByCommunityId($data['community_id'],$property['accredit']);
            //var_dump($resy);
            if (isset($resy['success'])) {
                $data['twocode'] = $resy['success']->community_services[0]->qr_code_image;
                $data['status'] = $resy['success']->community_status;
                $data['state']  = 4;
                $res = (new communityService())->communityEdit($data['community_id'], $data);
                return json(['info' => '申请上线成功']);
            }else{
                return json(['error' => $resy['error']]);
            }
        }else{
            return json(['error' => $res['error']]);
        }
    }

    //变更物业小区信息
    public function communityEdit() {
        $com = $this->pidTokenId();
        $where['id'] = array('in',$com['property_id']);
        //查询物业支付宝账号和token
        if (request()->isGet()) {
            if (!request()->has('id') || empty(request()->param('id'))) {
                $this->error('错误');
            }
            $propertylist =(new communityService())->propertyList($where);
            View::assign('propertylist',$propertylist);
            $id = request()->param('id');
            $info = (new communityService())->fetchCommunityByCommunityId($id);
            View::assign('info', $info);
            return View::fetch('community_edit');

        }else{
            $data = request()->param();
            //根据物业ID查询token
            $property = (new communityService())->propertyToken($data['property_id']);

            $api = new apiService(config('app')['update'], 'https://openapi.alipay.com/gateway.do');
            $res = $api->update(json_encode(['community_id' => $data['community_id'],'community_name' => $data['community_name'], 'community_address' =>  $data['community_address'], 'district_code' => $data['district_code'],'city_code' => $data['city_code'], 'province_code' => $data['province_code'], 'community_locations' => $data['community_locations'], 'hotline' => $data['hotline'], 'token' => $property['accredit']]));
            
            if (!isset($res['error'])) {
                if(isset($res['community_id'])){
                    $data['community_id'] = $res['community_id'];
                }
                $id = $data['community_id'];
                $d = [];
                foreach ($data as $key => $val) {
                    if (request()->has($key) && !empty(request()->param($key))) {
                        $d[$key] = request()->param($key);
                    }
                }
                $res = (new communityService())->communityEdit($id, $d);
                if($res) {
                    $this->success('修改成功');
                }else{
                    $this->error('修改失败');
                }
            }else{
                $this->error($res['error']);
            }
        }
    }
    
    //添加小区打印机
    public function printing(){
        if(request()->isGet()){
            if (!request()->has('id') || empty(request()->param('id'))) {
                $this->error('错误');
            }
            $id = request()->param('id');
            $info = (new communityService())->communityIdInfo($id);
            View::assign('info',$info);
            if($info){
                return View::fetch('community_printing');
            }else{
                return json(['info' => '小区信息错误']);
            }
        }else{
            //获取表单数据
            $data = request()->post();
            //将数据插入数据库
            $result = (new communityService())->communityprinting($data);
            //判断数据是否插入成功
            if($result){
                return "参数修改成功";
                $this->success('配置打印机成功',url('communitylist'));
            }else{
                $this->error('配置打印机失败',url('communitylist'));
            }
        }
    }
    
   
    public function psort(){
        if(request()->isGet()){
            if (!request()->has('id') || empty(request()->param('id'))) {
                $this->error('错误');
            }
            $id = request()->param('id');
            $info = (new communityService())->communityIdInfo($id);
            View::assign('info',$info);
            if($info){
                return View::fetch('community_psort');
            }else{
                return json(['info' => '小区信息错误']);
            }
        }else{
            //获取表单数据
            $data = request()->post();
            //将数据插入数据库
            $result = (new communityService())->communityprinting($data);
            //判断数据是否插入成功
            if($result){
                $this->success('提交成功',url('communitylist'));
            }else{
                $this->error('提交失败',url('communitylist'));
            }
        }
    }

    public function billset(){
        if(request()->isGet()){
            if (!request()->has('id') || empty(request()->param('id'))) {
                $this->error('错误');
            }
            $id = request()->param('id');
            $info = (new communityService())->communityIdInfo($id);
            View::assign('info',$info);
            if($info){
                
                return View::fetch('community_billset');
            }else{
                return json(['info' => '小区信息错误']);
            }
        }else{
            //获取表单数据
            $data = request()->post();
            //将数据插入数据库
            $result = (new communityService())->communityprinting($data);
            //判断数据是否插入成功
            if($result){
                return '修改成功';
                $this->success('提交成功',url('communitylist'));
            }else{
                $this->error('提交失败',url('communitylist'));
            }
        }
    }

    //查询单个小区信息
    public function communityIdInfo(){
        // 查询单个小区信息
        $community_id = 'ARYYP7RQA3301';//支付宝小区编号
        $token = '202007BBb5f8b77753a44991b5e7179ea5df1E83';//token
        $api = new apiService(config('app')['find'], 'https://openapi.alipay.com/gateway.do');
        $data = $api->fecthCommunityByCommunityId('ARYYP7RQA3301',$token);
        dump($data);exit();
        // 查询物业小区编号
        $api = new apiService(config('app')['select'], 'https://openapi.alipay.com/gateway.do');
        $data = $api->fetchCommunityId($token);
        dump($data);exit();
    }
    
    
    //查询小区信息
    public function communitycashier(){
        $data=request()->get();
        //查询小区信息
        $number =0;
        View::assign('number', $number);
        $data=Db::table("community_cashier")->select()->toArray();
        View::assign("list",$data);
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }
        return View::fetch('community_cashier');
    }
    public function communitycashierAdd(){
        //根据当前账号查询物业信息
        $com = $this->pidTokenId();
        
        $where['community_id'] = array('in',$com['community_id']);
        $communitylist =Db::name('community')->where($where)->select()->toArray();
        View::assign('communitylist',$communitylist);
        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();
            //查询该小区下的收银账号的数量
            $num=Db::table("community_cashier")->where("community_id",$data["community_id"])->count();
            if($num>=4){
                return "一个小区只能添加4个收银账号";
            }
            //判断小区是否重复
            $communityinfo=Db::table("community")->where("id",$data["community_id"])->find();
            //判断数据是否插入成功
            $data["community_name"]=$communityinfo["community_name"];
            $result=Db::table("community_cashier")->insert($data);
            if($result){
                return "添加成功";
            }else{
                $this->error('添加小区失败',url('communitycashierAdd'));
            }
        }else{
            
            return View::fetch('community_cashier_add');
        }
    }
    public function communitycashierEdit(){
        //根据当前账号查询物业信息
        $com = $this->pidTokenId();
        
        $where['community_id'] = array('in',$com['community_id']);
        $communitylist =Db::name('community')->where($where)->select()->toArray();
        View::assign('communitylist',$communitylist);
        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();
           
            
            $result=Db::table("community_cashier")->update($data);
            if($result){
                return "修改成功";
            }else{
                $this->error('修改失败');
            }
        }else{
           
            $cashier_id=request()->get("cashier_id");
            
            $info = Db::table("community_cashier")->where("id",$cashier_id)->find();
            if(empty($info)){
                return json(['info' => '小区信息错误']);
            }
            View::assign('info',$info);
            

        
            return View::fetch('community_cashier_edit');
        }
    }

    public function wxuseradd(){
        if(request()->isPost()){
            $data=request()->post();
            $res=Db::table("community_wxuser")->where("community_id",$data["community_id"])->where("openid",$data["openid"])->find();
            if(empty($res)){
                $info["community_id"]=$data["community_id"];
                $info["openid"]=$data["openid"];
                $re=Db::table("community_wxuser")->insert($info);
                if($re){
                    return "添加成功";
                }else{
                    return "添加失败";
                }
            }else{
                return "该用户已添加,不可重复添加";
            }
        }else{
            $id=request()->get("id");
            $communityinfo=Db::table("community")->where("id",$id)->find();
            View::assign("communityinfo",$communityinfo);
            $wxuserlist=Db::table("zz_wxuser")->select()->toArray();
            View::assign("wxuserlist",$wxuserlist);
            return View::fetch("community_wxuseradd");
        }

    }

    public function wxuserlist(){
        $community_id=request()->get("community_id");

        $userlist=Db::table("community_wxuser")
                    ->alias("a")
                    ->join("zz_wxuser b","a.openid=b.openid")
                    ->where("a.community_id",$community_id)
                    ->field("a.*,b.nickname,b.headimgurl")
                    ->select()->toArray();
        //echo "<pre>";
        //dump($userlist);die;
        View::assign("userlist",$userlist);
        return View::fetch("community_wxuserlist");
    }

    public function wxuserdel(){
        $id=request()->param("id");
        $userinfo=Db::table("community_wxuser")->where("id",$id)->find();
        if(empty($userinfo)){
            return "error";
        }
        $res=Db::table("community_wxuser")->where("id",$id)->delete();
        if($res){
            return "ok";
        }else{
            return "error";
        }
    }
}